package nl.scalasim
package controlactors

import scala.collection.mutable.HashMap
import scala.collection.Set
import nl.scalasim.actors.traits.{SimulationActor, ComposedActor, StoppableActor}
import nl.scalasim.util.Advertisements

/**
 * The guildmaster keeps track of all stored goods in the city. Citizens
 * can ask the guildmaster for the best spot to retrieve certain goods
 * using the FindGoods messages.  
 *
 * @author Yigal Duppen
 * @since Nov 18, 2010
 */
class Guildmaster extends ComposedActor
        with StoppableActor
        with Logging
{
  private val advertisements = new Advertisements[SimulationActor]()

  def handleAct: PartialFunction[Any, Unit] = {
    case Act => reply(Ack)
  }
  callbacks :+= handleAct


  def handleAdvertise: PartialFunction[Any, Unit] = {
    case Advertise(source, available) => {
      advertisements.advertise(source, available)
    }
  }
  callbacks :+= handleAdvertise


  def handleFindGoods: PartialFunction[Any, Unit] = {
    case FindGoods(from, goods) => {
      val actors: Set[SimulationActor] = advertisements.find(goods).filter(_ != from)

      actors.size match {
        case 0 => reply(Found(None))
        case _ => reply(Found(Some(actors.head))) // todo: add distance check
      }
    }
  }
  callbacks :+= handleFindGoods

}